$(function () {

      class Detail{
            constructor(){
                  this.c = 1
                  this.ID = cookie("productId")
                  // 传过来的数据时字符串 改为数字类型
                  this.ID = Number( this.ID )
                  this.getData()
                  this.count = 1
            }
            getData(){
                  var html_sign = cookie("html")
                  // 获取detail.json数据
                  var option = {
                        url : "http://localhost:3000/static/data/detail.json"
                  }
                  axios( option ).then( res => {
                        this.data = res.data[0]

                        // 获取list.jaon数据 (判断一下是哪个页面来的数据 再请求数据)
                        if( html_sign === "phonelist" ){
                              var option2 = {
                                    url : "http://localhost:3000/static/data/list-pull.json"
                              }
                        }else if( html_sign === "lifelist"){
                              var option2 = {
                                    url : "http://localhost:3000/static/data/list-pagination.json"
                              }
                        }
                        axios( option2 ).then( data => {
                              var list_data = data.data.resultList
      
                              for( var i = 0 ; i < list_data.length ; i ++ ){
                                    if( list_data[i].productId == this.ID ){
                                          this.list_data = list_data[i]
                                    }
                              }
                              this.leftRender()
                              new Swiper('.swiper-container', {
                                    slidesPerView: 5, 
                                    spaceBetween: 20,
                                    navigation: {
                                          nextEl: '.swiper-button-next',
                                          prevEl: '.swiper-button-prev',
                                    },
                              })
                              this.bigImgRender()
                              this.bindEvent()
                              new Magnifier()
                        })
                  })
            }
            bindEvent(){
                  // 大小图切换
                  $(".res .swiper-wrapper .swiper-slide img").each( (index , ele ) => {
                        on( ele , "mouseover" , a => {
                              this.bigRender( index , ele )
                              new Magnifier()
                        })
                  })
                  // box添加红色边框
                  $(".color .right .box").each( (index , ele) => {
                        on( ele , "click" , a => {
                              this.boxRed($(".color .right .box") , index )
                        })
                  })
                  $(".edition .right .box").on( "click" , a => {
                        $(".edition .right .box").addClass("box-red")
                  } )
                  $(".plan .right .box").each( (index , ele) => {
                        on( ele , "click" , a => {
                              this.boxRed($(".plan .right .box") , index )
                        })
                  })
                  $(".free .right .box").each( (index , ele) => {
                        on( ele , "click" , a => {
                              this.boxRed($(".free .right .box"), index )
                        })
                  })
                  $(".recommend .right .box").each( (index , ele) => {
                        on( ele , "click" , a => {
                              this.boxRed($(".recommend .right .box"), index )
                        })
                  })
                  // 添加数量 点击事件
                  $("#add").on( "click" , a => {
                        this.count++
                        $(".btns input").prop({ "value" : this.count })
                  })
                  $("#reduce").on( "click" , a => {
                        this.count--
                        if( this.count < 1) this.count = 1
                        $(".btns input").prop({ "value" : this.count })
                  })
                  // 添加购物车按钮 点击保存到session Storage
                  $(".cart").on( "click" , a => {
                        this.saveData()
                  })

                  // 弹窗 再逛逛
                  $("#right-render").on( "click" , ".cart" , a=> {
                        $("#gocart-render .gocart").css({display : "block"})
                        animate( $(".gocart")[0] , { opacity : 1 } )
                  })
                  $("#gocart-render").on( "click" , ".gocartleft" , a=> {
                        animate( $(".gocart")[0] , { opacity : 0 } )
                        // $("#gocart-render .gocart").css({display : "none"})
                  })
            }
            saveData(){
                  // 存入数据
                  var session_data = JSON.parse(localStorage.getItem("cart"))
                  
                  
                  var cart_data = {
                        title : this.list_data.skuName,
                        price : this.list_data.price ,
                        imgSrc : `https://res.vmallres.com/pimages/${this.list_data.photoPath}428_428_${this.list_data.photoName}`,
                        productId : this.list_data.productId ,
                        count : $(".btns input").prop("value"),
                        repricer : this.list_data.priceAccurate 
                  }
                  
                  // 判断session Storage中有没有这个数据  有的话只改变数量
                  if( session_data ){
                        for( var i = 0 ; i < session_data.length ; i++ ){
                              if( cart_data.productId === session_data[i].productId ){
                                    session_data[i].count = cart_data.count
                                    localStorage.setItem( "cart" , JSON.stringify(session_data))
                                    return;
                              }
                        }
                  }else{
                        session_data = []
                  }

                  console.log(cart_data);
                  // 没有的话直接存入
                  session_data.push(cart_data)
                  localStorage.setItem( "cart" , JSON.stringify(session_data))
                  
            }

            // 进入页面的大图
            bigImgRender(){
                  var html = `
                  <div class="big-focus">
                        <img src="https://res.vmallres.com/pimages/${this.list_data.photoPath}800_800_${this.list_data.photoName}" style="background-color:white;" alt="">
                  </div>`
                  $(".big").html( html )
            }

            boxRed( ele , index ){
                  ele.removeClass("box-red")
                  ele.eq(index).addClass("box-red")
            }

            // 大图渲染
            bigRender( index , ele ){
                  $(".res .swiper-wrapper .swiper-slide img"). removeClass("active")
                  $(".res .swiper-wrapper .swiper-slide img").eq(index).addClass("active")
                  // 获取大图路径
                  var src = ele.src
                  this.big_src = src.replace( /78_78_/g , "800_800_")
                  $(".mid img").eq(0).attr({ src : this.big_src })
                  var html = `
                  <div class="big-focus">
                        <img src="${this.big_src}" style="background-color:white;" alt="">
                  </div>`
                  $(".big").html( html )
            }
            // 全局渲染
            leftRender( big_src ){
                  // 渲染的时候判断下data里有没有这个数据 如果有就渲染 没有就跳过
                  var data = this.data
                  var list_data = this.list_data
                  // console.log(this.data , this.list_data);
                  var html = `
                        <div class="mid">
                              <img src="https://res.vmallres.com/pimages/${list_data.photoPath}800_800_${list_data.photoName}" class="mid-img" alt="">
                              <div class="focus"></div>
                              <div class="big big-focus">
                                    <div class="">
                                          <img src="https://res.vmallres.com/pimages/${list_data.photoPath}800_800_${list_data.photoName}" style="background-color:white;" alt="">
                                    </div>
                              </div>
                        </div>
                        <dt class="res">
                              <div class="swiper-container">
                                    <div class="swiper-wrapper">
                                          <div class="swiper-slide myWidth"><img class="active" src="https://res.vmallres.com/pimages/${list_data.photoPath}800_800_${list_data.photoName}" class="mid-img" alt=""></div>
                                          <div class="swiper-slide myWidth"><img src="${data.left[1]}" alt=""></div>
                                          <div class="swiper-slide myWidth"><img src="${data.left[2]}" alt=""></div>
                                          <div class="swiper-slide myWidth"><img src="${data.left[3]}" alt=""></div>
                                          <div class="swiper-slide myWidth"><img src="${data.left[4]}" alt=""></div>
                                          <div class="swiper-slide myWidth"><img src="${data.left[5]}" alt=""></div>
                                          <div class="swiper-slide myWidth"><img src="${data.left[6]}" alt=""></div>
                                    </div>
                              </div>
                              <div class="swiper-button-prev"></div><!--左箭头。如果放置在swiper-container外面，需要自定义样式。-->
                              <div class="swiper-button-next"></div><!--右箭头。如果放置在swiper-container外面，需要自定义样式。-->
                        </dt>`
                  $("#left-render").html( html )

                  html = `
                  <h3>${list_data.skuName}</h3>
                  <p>${data.tip}</p>
                  <div class="gray">
                  <div class="price">
                        <div class="left-margin price-left">价&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;格</div>
                        <dt class="right price-right">￥${list_data.price}</dt>
                  </div>
                  <div class="activity">
                    <div class="left-margin">促&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;销</div>
                    <dt class="right">`

                  for( var attr in data.active) {
                        html += `<div class="word"><span>${attr}</span>${data.active[attr]}</div>`
                  }
                  html += `
                              </dt>
                        </div>
                  </div>
                  <div class="server clear">
                        <div class="left-margin">服务说明</div>
                        <dt class="right">
                              <select name="server" id="server-select">
                              <option value="威海">威海</option>
                              <option value="北京">北京</option>
                              <option value="上海">上海</option>
                              <option value="广州">广州</option>
                              <option value="深圳">深圳</option>
                              <option value="曹县">曹县</option>
                              </select>
                        </dt>
                  </div>
                  <div class="code clear">
                        <div  class="left-margin">商品编码</div>
                        <dt class="right">${data.code}</dt>
                  </div>
                  <div class="color clear">
                        <div  class="left-margin">选择颜色</div>
                        <dt class="right clear">`

                  for( var attr in data.color ){
                        html += `
                        <div class="box">
                            <img src="${data.color[attr]}" alt="">
                            ${attr}
                        </div>`
                  }
                  html += `
                        </dt>
                  </div>
                  <div class="edition clear">
                        <div class="left-margin">选择版本</div>
                        <dt class="right">
                              <div class="box">
                              ${data.banben}
                              </div>
                        </dt>
                  </div>
                  <div class="plan clear">
                        <div class="left-margin">选择套餐</div>
                        <dt class="right">`
                  for( var i = 0 ; i < data.plan.length ; i++){
                        html += `<div class="box">${data.plan[i]}</div>`
                  }
                  html += `
                        </dt>
                  </div>
                  <div class="free clear">
                        <div class="left-margin">分期免息</div>
                        <dt class="right">`

                  for ( var i = 0 ; i < data.free.length ; i++ ){
                        html += `<div class="box">${data.free[i]}</div>`
                  }

                  html += `
                        </dt>
                  </div>
                  <div class="recommend  clear">
                        <div class="left-margin">推荐</div>
                        <dt class="flex right clear">`

                  for( var attr in data.recommend ){
                        html += `
                        <div class="box tr recommend-box-heigh clear">
                            <img src="${data.recommend[attr]}" alt="">
                            <div>${attr}</div>
                        </div>`
                  }

                  html += `
                        </dt>
                  </div>
                  <div class="selected clear">  
                        <div class="left-margin">已选商品</div>
                        <dt class="right">
                              <div class="red">${data.selector}</div>
                        </dt>
                  </div>
                  <div class="btns">
                        <input type="text" id="count" name="" value="1" >
                        <dl>
                              <dd id="add">+</dd>
                              <dd id="reduce">-</dd>
                        </dl>
                        <button class="cart">加入购物车</button>
                        <button class="buy">立即下单</button>
                  </div>`

                  $("#right-render").html( html )

                  html = `
                  <div class="gocart">
                        <div class="gocartup">
                              ${this.list_data.briefName} 成功加入购物车！
                        </div>
                        <div class="gocartdown">
                              <div class="gocartleft">
                                    再逛逛
                              </div>
                              <a href="http://localhost:3000/dist/cart.html" class="gocartright">
                                    去结算
                              </a>
                        </div>
                  </div>`
                  $("#gocart-render").html( html )

                  html = ''
                  for( var i = 0 ; i < data.img.length ; i ++ ){
                        html += `
                        <img src="${data.img[i]}" alt="">`
                  }
                  $("section").html( html )
            }
      }


      new Detail()

      class Magnifier{
            constructor(){
                  this.img = document.querySelector(".mid>img");
                  this.focus = document.querySelector(".focus");
                  this.big_img = document.querySelector(".big-focus");
                  this.big_bg = document.querySelector(".big-focus img");
                  this.midParent = document.querySelector(".main-left")
                  this.scale = 0.5;
                  // - 为了获取元素的偏移距离，计算正确的focus位置; 
                  this.container = document.querySelector(".mid");
                  this.scrollTop = null
      
                  this.init();

                  this.c_off = {
                        left : this.container.offsetLeft,
                        top  : this.container.offsetTop,
                  }
                  
                  // offset 家族是没办法测量 display 为none 的元素; 
                  this.f_style = getComputedStyle( this.focus ),
                  this.i_style = getComputedStyle( this.img ) 
      
                  // this.boundary.y.max
                  // 边界数据对象; 
                  this.boundary = {
                        x : {
                              min : 0,
                              max : parseInt(this.i_style.width) - parseInt(this.f_style.width)
                        },
                        y : {
                              min : 0 ,
                              max : parseInt(this.i_style.height) - parseInt(this.f_style.height)
                        }
                  }
                  this.bindEvent();
                  window.dispatchEvent( new Event("scroll"))
            }
            init(){   
                  // 需要修改
                  this.focus.style.width  = 450 * this.scale + "px";
                  this.focus.style.height = 450 * this.scale + "px";
      
                  this.big_img.style.width  = 800 * this.scale + "px";
                  this.big_img.style.height = 800 * this.scale + "px";
            }
            
            bindEvent(){
                  this.container.addEventListener("mouseenter" , ()=>{
                        animate( $(".big")[0] , { opacity : 1 } , '' , 'liner' , 10  )
                        this.show();
                        
                  })
                  this.container.addEventListener("mouseleave" , ()=>{
                        this.hide();
                        animate( $(".big")[0] , { opacity : 0 } )
                  })
                  //**** */
                  $("main").on( "mousemove" , ".mid" , (e)=> {
                        this.move(e.clientX , e.clientY);
                  })
                  // 获取滚动条高度 
                  window.onscroll = () =>{
                        this.top = document.documentElement.scrollTop
                  }
            }
            show(){
                  this.focus.style.display = "block";
                  $(".big-focus").css({display : "block"})
            }
            hide(){
                  this.focus.style.display = "none";
                  this.big_img.style.display = "none";
            }
            move( x , y ){
                  // 如果使用offset会出现 鼠标获取位置的参照物和focus元素定位的参照物不一致; 
                  // - 导致元素位移位置不正确; 
                  x =  x - this.c_off.left - parseInt(this.f_style.width) / 2;
                  y =  y - this.c_off.top - parseInt(this.f_style.height) / 2 + this.top;
                  // console.log( y , this.c_off.top , parseInt(this.f_style.height)  / 2 );

                  //  边界检测 
                  x = x <= this.boundary.x.min ? this.boundary.x.min : x ; 
                  x = x >= this.boundary.x.max ? this.boundary.x.max : x ; 

                  // BUG -225 225
                  console.log(this.boundary.y.max , parseInt(this.i_style.height) - parseInt(this.f_style.height));
                  this.boundary.y.max = Math.abs(this.boundary.y.max)
                  y = y <= this.boundary.y.min ? this.boundary.y.min : y ; 
                  y = y >= this.boundary.y.max ? this.boundary.y.max : y ; 
                  
                  this.focus.style.left = x + "px";
                  this.focus.style.top  = y + "px";
      
                  // 修改
                  this.big_bg.style.left = - x * ( 800 / 450 ) + "px";
                  this.big_bg.style.top  = - y * ( 800 / 450 ) + "px";

            }
      }
      
})




